package com.wxh.bomb.netty.echo.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;

/**
 * Echo 客户端
 *
 * @author wxh
 * @date：2017.10.19
 */
public class EchoClient {
    private final String host;
    private final int port;
    private final String clientName;

    public EchoClient(String host, int port, String clientName) {
        this.host = host;
        this.port = port;
        this.clientName = clientName;
    }

    /**
     * Echo客户端启动
     * <p>
     * 1. 创建一个ServerBootstrap实例
     * 2. 创建一个EventLoopGroup来处理各种事件，如处理链接请求，发送接收数据等。
     * 3. 定义一个远程InetSocketAddress好让客户端连接
     * 4. 当连接完成之后，Handler会被执行一次
     * 5. 所有准备好之后调用ServerBootstrap.connect()方法连接Server
     */
    private void run() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();                                //#1 创建 bootstrap 客户端
            b.group(group)                                                //#2 这里指定 NioEventLoopGroup 处理客户端事件
                    .channel(NioSocketChannel.class)                      //#3 指定通道类型
                    .remoteAddress(new InetSocketAddress(host, port))     //#4 设置绑定地址和端口
                    .handler(new ChannelInitializer<SocketChannel>() {    //#5 使用ChannelInitializer，指定通道处理器

                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            //设置特殊分隔符,使用分隔符拆包
                            ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));
                            //设置字符串形式的解码
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new EchoClientHandler());//#6 将EchoClientHandler加入到管道
                        }

                    });
            ChannelFuture f = b.connect().sync();                          //#7 连接到服务端
            f.addListener(new ChannelFutureListener() {

                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        System.out.println("client connected");
                    } else {
                        System.out.println("server attemp failed");
                        future.cause().printStackTrace();
                    }

                }
            });

            for (int i = 0; i < 1000; i++) {
                f.channel().writeAndFlush(Unpooled.copiedBuffer(("我是" + clientName + ", 你好！" + i + "$_").getBytes()));
            }


            f.channel().closeFuture().sync();                              //#8 阻塞直到客户端通道关闭
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                group.shutdownGracefully().sync();                         //#9 关闭线程池释放资源
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) throws Exception {
        final CountDownLatch latch = new CountDownLatch(1);
        new Thread(new Runnable() {
            public void run() {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                new EchoClient("127.0.0.1", 8080, "c1").run();
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                new EchoClient("127.0.0.1", 8081, "c2").run();
            }
        }).start();
        latch.countDown();
    }
}
